package com.xyhy.core.utils.crypto;

import java.util.Map.Entry;
import java.util.SortedMap;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import com.xyhy.core.utils.code.CodeUtil;

public class SHA256Util {
	public static String generateSign(SortedMap<String, String> signMaps, String mchKey) throws Exception {
		StringBuffer sb = new StringBuffer();

		// 字典序
		for (Entry<String, String> signMap : signMaps.entrySet()) {
			String key = (String) signMap.getKey();
			String value = (String) signMap.getValue();

			// 为空不参与签名、参数名区分大小写
			if (null != value && !"".equals(value) && !"sign".equals(key) && !"key".equals(key)) {
				sb.append(key).append("=").append(value).append("&");
			}
		}

		// 拼接key
		sb.append("key=").append(mchKey);
		// MD5加密
		String sign = HMACSHA256(sb.toString(), mchKey).toUpperCase();
		return sign;
	}

	public static String HMACSHA256(String data, String key) throws Exception {
		String hash = "";
		try {
			Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
			SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
			sha256_HMAC.init(secret_key);
			byte[] bytes = sha256_HMAC.doFinal(data.getBytes("UTF-8"));
//			hash = CodeUtil.byteArrayToHexString(bytes);
			hash = CodeUtil.byteArrayToHexStringTemp(bytes);
		} catch (Exception e) {
			System.out.println("Error HmacSHA256 ===========" + e.getMessage());
		}
		return hash.toUpperCase();
	}
}
